import { set } from "lodash";
import EventModel from "../model/EventModel";

/**
 * Create an event service that can be used to create events
 * @param {{ eventKey: string; eventData: any; eventDate: Date }[]} eventDataList - An array of objects
 * that contain the event key and the event data.
 * @returns The number of events created.
 */
export const createEventService = async (
  eventDataList: { eventKey: string; eventData: any; eventDate: Date }[] = [],
) => {
  const result = await EventModel.create(eventDataList);
  return result.length;
};

/**
 * It finds all events that match the given criteria.
 * @param {any} opts - any = {}
 * @param {Date | null} startDate - Date | null
 * @param {Date | null} endDate - Date | null
 * @returns An array of events.
 */
export const findEventsService = async (
  opts: any = {},
  startDate: Date | null,
  endDate: Date | null,
) => {
  startDate instanceof Date && set(opts, `eventDate.$gte`, startDate);
  endDate instanceof Date && set(opts, `eventDate.$lt`, endDate);
  const res = await EventModel.find(opts).sort({ eventDate: 1 }).limit(10);
  return res;
};
